using Joy.Erp.BasicArchives.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.DependencyInjection;
using Volo.Abp.EntityFrameworkCore.Modeling;

namespace Joy.Erp.BasicArchives.Production
{
    public class PlanOrderModelConfiguration : IModelConfiguration
    {
        public void Build(ModelBuilder builder)
        {
            builder.Entity<PlanOrder>(b =>
            {
                b.ToTable(BasicArchivesDbProperties.DbTablePrefix + nameof(PlanOrder), BasicArchivesDbProperties.DbSchema);
                b.ConfigureByConvention();
                b.ConfigureDocumentAggregateRoot<PlanOrder, PlanOrderPreparation>();

                b.Property(x => x.OrderTypeId).IsRequired(PlanOrderConsts.OrderTypeIdRequired);
                b.Property(x => x.ItemMasterId).IsRequired(PlanOrderConsts.ItemMasterIdRequired);
                b.Property(x => x.ItemCode).IsRequired(PlanOrderConsts.ItemCodeRequired);
                b.Property(x => x.ItemCode).HasMaxLength(PlanOrderConsts.ItemCodeMaxLength);
                b.Property(x => x.ItemName).IsRequired(PlanOrderConsts.ItemNameRequired);
                b.Property(x => x.ItemName).HasMaxLength(PlanOrderConsts.ItemNameMaxLength);
                b.Property(x => x.ItemSpec).HasMaxLength(PlanOrderConsts.ItemSpecMaxLength);
                b.Property(x => x.Quantity).HasColumnType(PlanOrderConsts.QuantityColumnType);
                b.Property(x => x.ReleaseQuantity).HasColumnType(PlanOrderConsts.ReleaseQuantityColumnType);
                b.Property(x => x.Mark).HasMaxLength(PlanOrderConsts.MarkMaxLength);

                b.HasOne(x => x.OrderType).WithMany().HasForeignKey(x => x.OrderTypeId).OnDelete(DeleteBehavior.Restrict);
                b.HasOne(x => x.ItemMaster).WithMany().HasForeignKey(x => x.ItemMasterId).OnDelete(DeleteBehavior.Restrict);

                b.HasMany(x => x.Children).WithOne(x => x.Document).HasForeignKey(x => x.DocumentId).OnDelete(DeleteBehavior.Cascade);
            });
        }

        public void Entity(IAbpDbContextRegistrationOptionsBuilder options)
        {
            options.Entity<PlanOrder>(opt =>
            {
                opt.DefaultWithDetailsFunc = query =>
                {
                    return query
                        .Include(x => x.OrderType)
                        .Include(x => x.ItemMaster)
                        .Include(x => x.Children)
                            .ThenInclude(x => x.ItemMaster)
                        ;
                };
            });
        }
    }
}